<?php

error_reporting(E_ALL);
ini_set('display_errors', 1);

/*
 * define a few variables we might need later
 */

$lp_install = isset($_POST['lp_install']) ? $_POST['lp_install'] : null;
$lp_message = isset($_GET['lp_message']) ? array($_GET['lp_message']) : array();
$lp_location = (isset($_SERVER['HTTPS']) ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'];
if (count($lp_message) > 0)
    $lp_location .= preg_replace('/&?lp_message=[^&]+/', '', $_SERVER['REQUEST_URI']);
else
    $lp_location .= $_SERVER['REQUEST_URI'];

/*
 * check if we have to reset LightPress options or change installation type
 */

if ($lp_install == 'reset') {
    $wpdb->query("delete from {$wpdb->options} where option_name like 'lp_opt_%'");
    wp_cache_flush();
    // the WP db/cache system is so screwed up we need to redirect the user
    header('Location: ' . preg_replace('/&?noheader=[^&]+/', '', $lp_location) . '&lp_message=Lightpress+Options+Cleared');
} else if ($lp_install == 'switch' && $lp_opts->getOption('install_type') != $lp_opts->getOption('install_type', false)) {
    //$lp_opts->updateOption('lp_opt_install_type', $lp_opts->getOption('install_type'));
    $lp_install = 'stage2';
} else if ($lp_install == 'comment_count') {
    $wpdb->query("update {$wpdb->posts} set comment_count = (select count(comment_ID) from {$wpdb->comments} where comment_post_id = ID and comment_approved = '1')");
    $lp_message[] = "Comment count synced.";
}

/*
 * do basic housekeeping tasks
 */

require_once('admin.php');

$title = 'Installation';
$this_file = 'lightpress/wp-plugin/main.php';
$parent_file = 'lightpress/wp-plugin/main.php';

$submenu[$this_file][] = array('LightPress', 'manage_options', 'lightpress/wp-plugin/main.php', 'LightPress');

/*
 * instantiate LightPressOptions and the Template object
 */

if (!isset($lp_opts)) {
    require_once 'LightPressOptions.php';
    $lp_opts = new LightPressOptions();
} else if (!is_object($lp_opts) || !is_subclass_of($lp_opts, 'LightPressOptions')) {
    $lp_opts = new LightPressOptions();
}

if (is_null($lp_install) && $lp_opts->critical === null)
    $lp_install = 'stage1';


require_once implode(DIRECTORY_SEPARATOR, array(dirname(dirname(__FILE__)), 'classes', 'Template.php'));
$tpl =& new Template(implode(DIRECTORY_SEPARATOR, array(dirname(__FILE__), 'templates-'.__('en_US','lp'))));

$tpl_vars = array(
    'message'=>$lp_message,
    'location'=>$lp_location,
    'home'=>get_option('home'),
    'basedir'=>is_null($lp_opts->basedir) ? htmlentities(dirname(dirname(__FILE__))) : htmlentities($lp_opts->basedir),
    'url'=>$lp_opts->getOption('url') ? $lp_opts->getDefault('url') : $lp_opts->getOption('url'),
    'siteurl'=>get_option('siteurl')
    );

switch ($lp_install) {
    
    case 'stage1':
        
        $permalink_structure = get_option('permalink_structure');
        if (empty($permalink_structure))
            $tpl_vars['message'][] = "Note that WordPress is set up to use 'dumb' permalinks (like <code>{$tpl_vars['home']}/?p=1</code>). With this configuration the Lightpress installation is more complicated, and your blog will get less love from search engines. If this is not what you want, <a href=\"{$tpl_vars['url']}/wp-admin/options-permalink.php\">set a Permalink Structure</a> in WordPress then come back here to install Lightpress.";
        
        $tpl_vars['testing_folder_class'] = isset($_GET['lp_testing_folder_empty']) ? 'field_warning' : '';
        
        $tpl->setFile('main', 'step1.html');
        
        break;
        
    case 'stage2':
        
        // check if the user requested a test install with no testing directory name
        if ($lp_opts->getOption('install_type') == 'testing' && !$lp_opts->getOption('testing_dir'))
            header('Location: ' . preg_replace('/&?noheader=[^&]+/', '', $lp_location) . '&lp_message=Please+set+the+Lightpress+folder+name+if+you+want+a+test+install.&lp_testing_folder_empty=true');
        
        $opts = array('testing_dir', 'install_type', 'lang', 'copyright_notice', 'date_format', 'short_date_format',
                      'time_format', 'short_time_format', 'shortname', 'mail_on_comment', 'approx_sql_tstamp', 'allowed_tags');
        
        foreach ($opts as $opt)
            $tpl_vars[$opt] = htmlentities($lp_opts->getOption($opt));
        
        $tpl->setFile('main', 'step2.html');
        
        break;
        
    case 'stage3':
        
        $tpl->setFile('main', 'step3.html');
        
        foreach ($lp_opts->critical as $opt)
            $lp_opts->updateOption("lp_opt_$opt", $lp_opts->getOption($opt));
        foreach ($lp_opts->base as $opt=>$default)
            $lp_opts->updateOption("lp_opt_$opt", $lp_opts->getOption($opt));
        $lp_opts->updateOption('lp_opt_install_type', $lp_opts->getOption('install_type'));

        get_alloptions();
        
        $tpl_vars['wp_install_dir'] = get_home_path();
        
        $install_type = get_option('lp_opt_install_type');
        $home_path = get_home_path();
        
        if (substr($home_path, -1) != DIRECTORY_SEPARATOR)
            $home_path = substr($home_path, 0, -1) . DIRECTORY_SEPARATOR;
        if ($install_type == 'testing')
            $home_path .= substr(get_option('lp_opt_url'), strlen(get_option('home')) + 1);
        if (substr($home_path, -1) != DIRECTORY_SEPARATOR) {
            if (substr($home_path, -1) == '/')
                $home_path = substr($home_path, 0, -1);
            $home_path .= DIRECTORY_SEPARATOR;
        }
        $tpl_vars['home_path'] = $home_path;

        if ($install_type == 'testing' && !is_dir($tpl_vars['home_path'])) {
            if (DIRECTORY_SEPARATOR == '/') {
                $tpl_vars['mkdir'] = 'mkdir';
                $tpl_vars['mkdir_path'] = str_replace(' ', '\ ', $tpl_vars['home_path']);
            } else {
                $tpl_vars['mkdir'] = 'md';
                $tpl_vars['mkdir_path'] = '"' . $tpl_vars['home_path'] . '"';
            }
        } else {
            $tpl->setBlock('main', 'testing', 'TESTING');
            $tpl_vars['TESTING'] = '';
        }
        
        if (!get_option('lp_opt_post_prefix')) {
            $tpl_vars['message'][] .= "Lightpress needs additional installation tasks since you are using 'dumb' permalinks like {$tpl_vars['home']}/?p=1.
            If this is not what you want, <a href=\"{$tpl_vars['url']}/wp-admin/options-permalink.php\">set
            a Permalink Structure</a> in Wordpress, then <a href=\"{$tpl_vars['url']}/wp-admin/admin.php?page=lightpress/wp-plugin/main.php\">clear
            your Lightpress configuration</a> to start over.";
        }
        
        // check if we can write our config.php
        $config = $lp_opts->basedir . DIRECTORY_SEPARATOR . 'config.php';
        if ($f = @fopen($config, 'wb')) {
            $ret = @fwrite($f, $lp_opts->getConfig());
            @fclose($f);
            if ($ret) {
                $tpl->setBlock('main', 'config', 'CONFIG');
                $tpl->setVar('CONFIG', '');
            }
        }
        
        // check if we are using mod_rewrite, and try to write it
        $using_htaccess = false;
        if (get_option('lp_opt_post_prefix') && $wp_rewrite->using_mod_rewrite_permalinks()) {
            // try to write a new .htaccess file
            if ($install_type == 'root') {
                if ($lp_opts->updateRewriteRules('root')) {
                    // we managed to write the .htaccess file
                    $tpl_vars['htaccess_message'] = "check that permalinks work; if not, save the
                    <a href=\"{$tpl_vars['siteurl']}/wp-admin/admin.php?page=lightpress/wp-plugin/mod_rewrite.php&noheader=1\">Apache mod_rewrite rules</a>
                    to <code>$home_path.htaccess</code>";
                } else {
                    // we cannot write the .htaccess file ourselves
                    $tpl_vars['htaccess_message'] = "save the
                    <a href=\"{$tpl_vars['siteurl']}/wp-admin/admin.php?page=lightpress/wp-plugin/mod_rewrite.php&noheader=1\">Apache mod_rewrite rules</a>
                    to <code>$home_path.htaccess</code>";
                }
            } else {
                // the user has to manually copy the .htaccess file to the testing dir
                $tpl_vars['htaccess_message'] = "save the
                <a href=\"{$tpl_vars['siteurl']}/wp-admin/admin.php?page=lightpress/wp-plugin/mod_rewrite.php&noheader=1\">Apache mod_rewrite rules</a>
                to <code>$home_path.htaccess</code>";
            }
            $using_htaccess = true;
        } else {
            // show the user how to to manually write the .htaccess file
            // in case WP's autodetection missed something
            $tpl_vars['htaccess_message'] = "if you are using 'nice' permalinks like <code>http://{$tpl_vars['home']}/archive/2006/04/26/post-name</code>, and your server supports mod_rewrite rules, save the
            <a href=\"{$tpl_vars['siteurl']}/wp-admin/admin.php?page=lightpress/wp-plugin/mod_rewrite.php&noheader=1\">Apache mod_rewrite rules</a>
            to <code>$home_path.htaccess</code>; according to WordPress autodetection, you can safely skip this step";
        }
            
        if ($using_htaccess) {
            $tpl->setBlock('main', 'extra', 'EXTRA');
            $tpl_vars['EXTRA'] = '';
        } else {
            if (DIRECTORY_SEPARATOR == '/') {
                $tpl_vars['move_command'] = 'mv';
                $tpl_vars['copy_command'] = 'cp';
                $tpl_vars['home_path_command'] = str_replace(' ', '\ ', $tpl_vars['home_path']);
                $tpl_vars['basedir_command'] = str_replace(' ', '\ ', $tpl_vars['basedir']);
            } else {
                $tpl_vars['move_command'] = 'move';
                $tpl_vars['copy_command'] = 'copy';
                $tpl_vars['home_path_command'] = '"' . $tpl_vars['home_path'] . '"';
                $tpl_vars['basedir_command'] = '"' . $tpl_vars['basedir'] . '"';
            }
        }
            
        break;
        
    default:
        
        $tpl_vars['root_checked'] = $tpl_vars['testing_checked'] = '';
        
        $install_block = 'switch_to_' . $lp_opts->getOption('install_type');
        
        $tpl->setFile('main', 'main.html');
        $tpl->setBlock('main', $install_block);
        $tpl->setVar(strtoupper($install_block), '');
    
}

if (count($tpl_vars['message']) == 0) {
    $tpl_vars['message'] = '';
    $tpl->setBlock('main', 'message', 'message');
} else {
    $tpl_vars['message'] = implode('</p><p>', $tpl_vars['message']);
}

$tpl->setVar($tpl_vars);
$out =& $tpl->parse('MAIN', 'main');
echo $out;

?>
